<template>
  <div>
    <van-nav-bar title="报名情况" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="van_card">
        <div class="van_card_title eventnumber">会议编号：{{eventId}}</div>
      </div>
      <QuickSearch :quickSearch="quickSearch" @getSearchInfo="filterList"></QuickSearch>
      <div v-if="showSalesRegion" class="sendEmail van_card">
        <van-form @submit="onSubmit" :show-error="false">
          <van-field
            v-model="username"
            label="填写您的邮箱"
            placeholder="请输入您的邮箱"
            :rules="[{validator, required: true, message: '请填写正确的邮箱地址' }]"
          />
          <div>
            <van-button size="small" type="info">发送报名信息至邮箱</van-button>
          </div>
        </van-form>
      </div>
      <div v-if="searchList.length===0" class="van_card">
        <van-empty image="search" description="没有数据" />
      </div>

      <div class="van_card approvel_item" v-for="(item, j) in hasfilterList" :key="j">
        <p>旅客：{{ item.HCPName }}</p>
        <div class="joinGroup">
          <van-button
            :type="item.IsHCPAttendsMeeting=='Y'?'info':'default'"
            @click="change_m(item,j,true)"
            size="small"
          >确认参会</van-button>
          <van-button
            :type="item.IsHCPAttendsMeeting=='N'?'info':'default'"
            size="small"
            @click="change_m(item,j,false)"
          >取消参会</van-button>
        </div>
        <p v-if="showSalesRegion">填写人：{{ item.SalesRegion }}</p>
        <p>名单来源：{{ item.collectSource }}</p>
        <p v-if="!item.trips">出行日期：{{ item.sd+' - '+item.ed}}</p>
        <p
          v-if="item.trips"
        >出行日期：{{item.date.split('_-_')[0]}} {{item.date.split('_-_')[1]?"- "+item.date.split('_-_')[1]:''}}</p>
        <p v-if="item.flightt">
          <van-row>
            <van-col span="4">机票：</van-col>
            <van-col span="12">
              {{ item.flightt.split('_-_')[0] }}
              <br />
              {{ item.flightt.split('_-_')[1] }}
            </van-col>
            <van-col span="8">
              <span>{{ item.status.split('/')[0] }}</span>
              <br />
              <span v-if="!(item.flightt&&item.traint)">{{item.status.split('/')[1] }}</span>
            </van-col>
          </van-row>
        </p>
        <p v-if="item.traint">
          <van-row>
            <van-col span="4">火车票：</van-col>
            <van-col span="12">
              {{ item.traint.split('_-_')[0] }}
              <br />
              {{ item.traint.split('_-_')[1] }}
            </van-col>
            <van-col span="8">
              <span v-if="!(item.flightt&&item.traint)">{{ item.status.split('/')[0] }}</span>
              <br v-if="!(item.flightt&&item.traint)" />
              <span>{{ item.status.split('/')[1] }}</span>
            </van-col>
          </van-row>
        </p>
        <div class="operate_area" style="margin-top:10px">
          <van-button type="info" size="mini" @click="goReservation(item)">大交通预订</van-button>
          <van-button type="info" size="mini" @click="editEnroll(item.UCICode)">报名信息详情</van-button>
          <van-button
            type="info"
            :disabled="!item.trips"
            size="mini"
            @click="goApprovalIndividual(item)"
          >大交通信息详情</van-button>
          <van-button
            class="operate_area_del"
            type="danger"
            size="mini"
            @click="delete_trans(item)"
          >删除</van-button>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import QuickSearch from "../components/quickSearch";
import apilist from "../utils/apiList";
export default {
  data() {
    return {
      isLoading: false,
      username: "",
      searchList: [],
      quickSearch: {
        name: "",
        tripDate: "",
        status: "",
        listResource: "",
      },
      eventId: "",
      accountname: "",
      hasfilterList: [],
      showSalesRegion: true,
    };
  },
  created() {
    this.getAxiosData();
  },
  methods: {
    onRefresh() {
      window.location.reload();
    },
    // 发送邮件至邮箱
    // 邮箱验证
    validator(val) {
      let reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
      return reg.test(val);
    },
    onSubmit() {
      let t = this.hasfilterList.map((attendee) => {
        let exportedAttendee = {
          UCICode:
            attendee.UCICode.indexOf("__") > -1 ? "无" : attendee.UCICode,
          HCP姓名: attendee.HCPName,
          HCP单位所在城市: attendee.HCPCompanyCity,
          参会状态: attendee.IsHCPAttendsMeeting
            ? attendee.IsHCPAttendsMeeting == "Y"
              ? "确认参会"
              : "取消参会"
            : "待确认",
          HCP性别: attendee.HCPGender,
          HCP所在城市: attendee.HCPCity,
          HCP手机号: attendee.HCPMobile,
          HCP所在医院: attendee.HCPHospital,
          HCP证件类型: attendee.HCPIDType,
          HCP所在科室: attendee.HCPDepartment,
          HCP证件号: attendee.HCPIDNo,
          HCP职位: attendee.HCPJobTitle,
          客户类型: attendee.AttendeeType,
          房间需求: attendee.RoomType,
          "HCP是否为本次会议主席or讲者": attendee.IsSpeaker,
          同住人: attendee.RoomShareWith,
          是否需要大交通: attendee.IsNeedBigTransportation,
          飞机: attendee.FlightFlag,
          火车: attendee.TrainFlag,
          负责同事姓名: attendee.StaffName,
          负责同事手机号: attendee.StaffMobile,
          现场陪同人员: attendee.StaffNameInMeeting,
          现场陪同人员手机号: attendee.StaffMobileInMeeting,
          备注: attendee.Remark,
          填写人: attendee.fillname,
          时间戳记: (
            attendee.CreateTimeSpan ||
            attendee.SignedSSOTimeSpan ||
            ""
          ).replace(/T/g, " "),
          去程出票状态: attendee.DepartTicketStatus,
          去程交通工具: attendee.DepartProductDescription,
          去程出发日期: (attendee.DepartDate || "").split("T")[0],
          "去程航班号or列车班次": attendee.DepartFlightTrainNo,
          "去程航班号or列车出发时间": (attendee.DepartStartTime || "").split(
            "T"
          )[0],
          "去程航班号or列车抵达时间": (attendee.DepartEndTime || "").split(
            "T"
          )[0],
          返程出票状态: attendee.ReturnTicketStatus,
          返程交通工具: attendee.ReturnProductDescription,
          返程出发日期: (attendee.ReturnDate || "").split("T")[0],
          "返程航班号or列车班次": attendee.ReturnFlightTrainNo,
          "返程航班号or列车出发时间": (attendee.ReturnStartTime || "").split(
            "T"
          )[0],
          "返程航班号or列车抵达时间": (attendee.ReturnEndTime || "").split(
            "T"
          )[0],
          去程出发城市: attendee.DepartOrigCity,
          返程出发城市: attendee.ReturnOrigCity,
          行程备注: attendee.TripRemark,
        };
        return exportedAttendee;
      });
      let a = {
        mail: this.username,
        mail_title: this.eventId + "_名单收集数据",
        attendeeList: t,
      };
      this.$axios
        .post(apilist[1] + "/SendAttendeeEmail", JSON.stringify(a))
        .then((res) => {
          if (res.status == 200) {
            this.$notify({
              type: "success",
              message: "邮件发送成功",
            });
            this.username = "";
          }
        });
    },
    // 获取页面数据
    async getAxiosData() {
      let join = sessionStorage.getItem("join");
      // 是否显示邮件填写框和填写人
      if (join == 1) {
        this.showSalesRegion = false;
      }
      let eventid = JSON.parse(sessionStorage.getItem("eventid"));
      this.eventId = eventid;
      let accountname = JSON.parse(sessionStorage.getItem("accountname"));
      this.accountname = accountname.cName;
      // let res = await this.$axios({
      //   method: "get",
      //   url: apilist[0] + "/GetEvent?eventid=" + eventid,
      //   noloading: true,
      // });
      let login = JSON.parse(sessionStorage.getItem("event"));
      let res1 = await this.$axios({
        method: "get",
        url: apilist[0] + "/GetAttendeeListByEventid?eventid=" + eventid,
        noloading: true,
      });
      res1.data = res1.data.filter((v, i) => {
        return v.SignedID !== "D";
      });
      let p = res1.data;
      p.map(function (v, i) {
        if (
          v.IsStaffAttendDinnerParty == "P" ||
          v.IsStaffAttendDinnerParty == "p"
        ) {
          v.collectSource = "预录入";
        } else {
          v.collectSource = "新添加";
        }
        var sd = new Date(
          new Date(login.StartDate).getTime() - 3600 * 24 * 1000
        ).format("yyyy-MM-dd");
        var ed = new Date(
          new Date(login.EndDate).getTime() + 3600 * 24 * 1000
        ).format("yyyy-MM-dd");
        console.log(sd);
        v.date = sd + "_-_" + ed;
        v.travel = v.HCPName;
        v.sd = sd;
        v.ed = ed;
        v.fillname = v.SalesRegion;

        v.flightt = "";
        v.traint = "";
        v.date = "";
        v.start = true;
        if (!v.status) v.status = "";
      });
      p = p.filter(function (v, i, arr) {
        //||v.SalesRegion==account.account
        return (
          (sessionStorage.getItem("join") == 1 &&
            v.IsStaffAttendDinnerParty != "P" &&
            v.SalesRegion == accountname.cName) ||
          //||(!((v.IsStaffAttendDinnerParty=='P'||v.IsStaffAttendDinnerParty=='p')&&!v.HCPMobile))
          sessionStorage.getItem("join") != 1
        );
      });
      let p0 = p;
      let NextDay = new Date().getnextday("yyyy-MM-dd");
      let myDate = new Date();
      let lw = new Date(myDate.getTime() - 1000 * 60 * 60 * 24 * 30).format(
        "yyyy-MM-dd"
      );
      const res2 = await this.$axios.get(
        apilist[1] +
          "/GetStaffTripsByEventID?eventid=" +
          login.IDNo +
          "&start=" +
          lw +
          "&end=" +
          NextDay
      );
      let newp = res2.data.reverse();
      let g = p0;
      newp.sort(function (b, a) {
        return a.No.split("-")[1] - b.No.split("-")[1];
      });
      for (var ind = newp.length - 1; ind >= 0; ind--) {
        var v = newp[ind];
        var flightt = "";
        var _date = "";
        var traint = "";
        var order_st = "";
        var ve = v.ExorderList;
        var allc = false;
        var oe = v.ExorderList;
        if (v.Status == "已取消") {
          v.Status = "审批不通过";
        }
        if (oe.length == 0) {
          p.splice(ind, 1);
          continue;
        }
        oe.sort(function (a, b) {
          return (
            new Date(a.DepartureDate.replace(/-/g, "/")).getTime() -
            new Date(b.DepartureDate.replace(/-/g, "/")).getTime()
          );
        });
        ve.map(function (h, k) {
          if (h) {
            if (h.Remark3 && h.OrderStatus == "已取消") {
              h.OrderStatus = "审批不通过";
            } else {
              if (h.OrderStatus == "已取消") {
                h.OrderStatus = "取消审批";
              }
            }
            var stttt = h.OrderStatus;
            order_st += stttt + "/";
            if (h.ProductCat == "F") {
              flightt += h.OrigRemark + " / " + h.DestRouteRemark + "_-_";
            }
            if (h.ProductCat == "T") {
              if (h.ExorderTrainList[0]) {
                traint +=
                  h.ExorderTrainList[0].RoutingStart +
                  " / " +
                  h.ExorderTrainList[0].RoutingEnd +
                  "_-_";
              } else {
                traint += h.OrigAirport + " / " + h.DestRouteAirport + "_-_";
              }
            }
            if (h.DepartureDate) {
              _date += h.DepartureDate.split(" ")[0] + "_-_";
            }
          }
        });
        g.map(function (v0, i0) {
          if (v0.UCICode == v.ExorderList[0].TravelArrangerStaffNo) {
            if (v0.start) {
              v0.date = "";
              v0.start = false;
            }
            v0.trips = v;
            v0.flightt += flightt;
            v0.traint += traint;
            v0.date += _date;
            v0.MnlOrderNo = v.MnlOrderNo;
            v0.status += order_st;
          }
        });
      }
      this.searchList = p;
      this.hasfilterList = this.searchList;
    },
    // 发送邮件

    // 去个人详情页面
    goApprovalIndividual(item) {
      const PaxStaffNo = item.UCICode;
      sessionStorage.setItem("trdetail", JSON.stringify(item));
      this.$router.push({
        path: "/approvelIndividual",
        query: {
          PaxStaffNo: PaxStaffNo,
          eventid: this.eventId,
          lcsubmit: "lcsubmit",
          Status: "退票",
        },
      });
    },
    // 删除当前报名信息
    delete_trans: function (data) {
      console.log(data);
      var _this = this;
      var all_St = data.status.split("/");
      var xpd = true;
      all_St.map(function (v, i) {
        if (
          data.trips &&
          v &&
          (v == "已出票" || v == "已改期" || v == "被改签")
        ) {
          xpd = false;
          // _this.$notify({
          //   type: "danger",
          //   message: "请先进行退票再删除",
          //   duration: 1000,
          // });
          // control = false;
        }
      });
      if (!xpd) {
        data.IsHCPAttendsMeeting = "N";
        this.join(data, false);
        this.$notify({
          type: "danger",
          message:
            "由于该HCP已有出票信息，请先申请退票，同时将该HCP的参会状态改为“取消参会”",
        });
        return;
      }
      console.log(data);
      this.$dialog
        .confirm({
          title: "提示",
          message: "确定删除吗",
        })
        .then(() => {
          let deapi = "DeleteAttendee";
          if (
            sessionStorage.getItem("join") == 1 &&
            (data.IsStaffAttendDinnerParty == "P" ||
              data.IsStaffAttendDinnerParty == "p")
          ) {
            deapi = "DeleteAttendeeByDB";
          }
          this.$axios
            .get(apilist[0] + "/" + deapi + "?attendeeid=" + data.AttendeeID)
            .then((e) => {
              if (e.data != "success") {
                this.$notify({
                  type: "danger",
                  message: "删除失败",
                  duration: 1000,
                });
                return;
              } else {
                window.location.reload();
              }
            });

          // on confirm
        })
        .catch(() => {
          // on cancel
        });
    },
    // 筛选当前数组
    filterList(search) {
      this.hasfilterList = this.searchList;
      // if (search.status === "全部") {
      this.hasfilterList = this.hasfilterList.filter((v) => {
        const searchTime = new Date(search.tripDate).getTime();
        const startTime = new Date(v.sd.replace(/-/g, "/")).getTime();
        const endTime = new Date(v.ed.replace(/-/g, "/")).getTime();
        // console.log("1", v.date);
        // console.log(search.startDate);
        // console.log(new Date(v.date.split(" - ")[0].replace(/-/g,"/")));
        // console.log("搜索时间",searchTime);
        // console.log("开始时间",startTime);
        // console.log("结束时间",endTime);
        return (
          (search.name ? v.HCPName.indexOf(search.name) !== -1 : true) &&
          (searchTime ? startTime <= searchTime : true) &&
          (searchTime ? endTime >= searchTime : true) &&
          (search.status && search.status !== "全部"
            ? v.status.indexOf(search.status) !== -1
            : true) &&
          (search.listResource && search.listResource !== "全部"
            ? v.collectSource.indexOf(search.listResource) !== -1
            : true)
        );
      });
    },
    onClickLeft() {
      this.$router.push("/navigatorIndex");
    },
    // 修改是否参与会议
    change_m: function (data, index, status) {
      console.log(data, index, status);
      // if (data.IsHCPAttendsMeeting == "Y") {
      //   this.$notify({ type: "warning", message: "已确认参会后状态不能修改!" });
      //   return;
      // }
      let tip = "";
      if (status) {
        tip = "是否确认参会？";
      } else {
        tip = "是否取消参会？";
        if (data.IsHCPAttendsMeeting == "N") {
          return;
        }
      }
      this.$dialog
        .confirm({
          title: "提示",
          message: tip,
        })
        .then(() => {
          this.join(data, status);
        })
        .catch(() => {
          // on cancel
        });
    },
    join: function (data, status) {
      let api = status ? "ConfirmAttendsMeeting" : "CancelAttendsMeeting";
      this.$axios
        .get(apilist[0] + "/" + api + "?attendeeid=" + data.AttendeeID)
        .then((res) => {
          if (res.data == "success") {
            if (status) {
              data.IsHCPAttendsMeeting = "Y";
            } else {
              data.IsHCPAttendsMeeting = "N";
            }
          }
        })
        .catch((error) => {
          this.$notify({ type: "danger", message: "保存失败!" });
        });
    },
    // 去预定票页面
    async goReservation(item) {
      let eventid = JSON.parse(sessionStorage.getItem("eventid"));
      // let res = await this.$axios.get(
      //   apilist[0] + "/GetEvent?eventid=" + eventid
      // );
      let eventData = JSON.stringify(sessionStorage.getItem("event"));

      if (eventData.Status < 40 && eventData.Status != -1) {
        this.$notify({
          type: "danger",
          message: "现阶段DOA尚未审批会议,无法订票,请耐心等待",
          duration: 2000,
        });
        return;
      }
      if (
        eventData.Status == "-1" ||
        eventData.Status == "-2" ||
        eventData.Status == "-3" ||
        eventData.Status == "10" ||
        eventData.Status == "70" ||
        eventData.Status == "51" ||
        eventData.Status == "30" ||
        eventData.CollectStatus == "P" ||
        new Date(eventData.StartDate).getTime() < new Date().getTime() ||
        new Date(eventData.CollectEndDate).getTime() + 24 * 3600 * 1000 <
          new Date().getTime()
      ) {
        // if(sessionStorage.getItem('join')==1){
        this.$notify({
          type: "danger",
          message: "您好, 会议名单收集已经截止, 不再接收新增客户!",
          duration: 2000,
        });
        return;
        // }
        // return;
      }
      item.eventId = eventid;
      item.city = item.HCPCity == item.HCPCompanyCity;
      item.FlightFlag = item.FlightFlag != "N";
      item.TrainFlag = item.TrainFlag != "N";
      sessionStorage.setItem("book_trans", JSON.stringify(item));
      this.$router.push({
        path: "/reservation",
      });
    },
    // 删除当前人的草稿
    sketchDelect(id) {},
    // 去报名页面编辑
    editEnroll(ucicode) {
      console.log("去编辑");
      window.location.href =
        "https://ezway.efasco.com/roche_meeting/dist/newhcp.html?eventId=" +
        this.eventId +
        "&acc0=" +
        this.accountname +
        "&ucicode=" +
        ucicode +
        "&originpath=" +
        window.location.origin +
        window.location.pathname;
    },
  },
  components: {
    QuickSearch,
  },
};
</script>

<style lang="less" scoped>
.joinGroup {
  position: absolute;
  right: 15px;
  top: 15px;
}
.operate_area {
  .operate_area_del {
    float: right;
  }
}
</style>